package base

import (
	"fmt"
	"sync/atomic"
	"time"
)

func Int32Add() {
	var i int32
	go func() {
		atomic.AddInt32(&i, 1)
		fmt.Printf("原子操作1, i=%d\n", i)
	}()

	go func() {
		atomic.AddInt32(&i, 2)
		fmt.Printf("原子操作2, i=%d\n", i)
	}()
}

func Uint32Add() {
	var i uint32
	go func() {
		atomic.AddUint32(&i, 2)
		fmt.Printf("原子操作1, i=%d\n", i)
	}()

	go func() {
		var d int32
		d = -1
		atomic.AddUint32(&i, uint32(d))
		fmt.Printf("原子操作2, i=%d\n", i)
	}()
}

func Int32CompareAndSwap() {
	var i uint32
	i = 10
	go func(val *uint32) {
		time.Sleep(time.Millisecond * 1000)
		i++
		fmt.Printf("i自增, i=%d\n", i)
	}(&i)

	for {
		if atomic.CompareAndSwapUint32(&i, 11, 0) {
			fmt.Printf("对比并交换成功, i=%d\n", i)
			break
		}
	}
}

func StoreVal() {
	var box atomic.Value
	val := 1
	box.Store(val)
	val = 2
	box.Store(val)
	fmt.Println(box, val, box.Load())
}